package hehe.log.collect.async;

import hehe.log.base.Collect;
import hehe.log.base.Logger;
import hehe.log.base.Message;
import hehe.log.base.Target;
import hehe.log.collect.SyncCollect;
import hehe.log.util.LogUtil;

import java.util.Map;
import java.util.Vector;

/**
 * 同步收集
 *<B>说明：</B>
 *<pre>
 * 略
 *</pre>
 *<B>示例：</B>
 *<pre>
 *  略
 *</pre>
 *<B>日志：</B>
 *<pre>
 *  略
 *</pre>
 *<B>注意事项：</B>
 *<pre>
 *  略
 *</pre>
 */
public class AsyncCollect extends Collect
{

    /**
     * 日志列表
     *<B>说明：</B>
     *<pre>
     * 线程安全
     *</pre>
     */
    Vector<Message> messages = new Vector<>();

    Thread daemon;

    /**
     * 刷新日志数量
     *<B>说明：</B>
     *<pre>
     *  略
     *</pre>
     */
    protected int flushQuantity = 10;

    public AsyncCollect()
    {
        // 启动守护线程
        Thread daemon1 = new Thread(new Daemon(this));
        daemon1.setDaemon(true);
        daemon1.setName("AsyncAppender-Dispatcher-" +  daemon1.getName());

        Thread daemon2 = new Thread(new Daemon(this));
        daemon2.setDaemon(true);
        daemon2.setName("AsyncAppender-Dispatcher-" +  daemon2.getName());


        daemon2.start();
        daemon1.start();
    }


    public void append(Message message)
    {
        // 日志入队列
        this.messages.add(message);
    }

    /**
     * 是否刷新
     *<B>说明：</B>
     *<pre>
     *  略
     *</pre>
     */
    public boolean isFlush()
    {
        if (this.messages.size() > 0 && this.flushQuantity > 0 && this.messages.size() >= this.flushQuantity) {
            return true;
        }

        return false;
    }

    /**
     * 日志消息存储
     *<B>说明：</B>
     *<pre>
     * 略
     *</pre>
     */
    public void flushMessage()
    {
        Vector<Message> messageList;
        // 刷新日志时,先锁住消息,防止其他线程同时访问
        synchronized(this.messages) {
            if (!this.isFlush()) {
                return ;
            }

            System.out.println("start flush total:" + this.messages.size() + ",time:" + Math.random() +
                ",threadid" + Thread.currentThread().getId()
            );

            // 复制消息
            messageList = (Vector)this.messages.clone();
            // 清空目前消息
            this.messages.clear();
        }

        // 将日志存储至文件或其他存储设备
        for (Target target:this.logger.getTargets()) {
            target.collect(messageList);
        }
    }
}
